package cn.lh.org.service.impl;

import cn.lh.basic.service.impl.BaseServiceImpl;
import cn.lh.basic.util.Md5Utils;
import cn.lh.basic.util.StrUtils;
import cn.lh.org.domain.Employee;
import cn.lh.org.mapper.EmployeeMapper;
import cn.lh.org.service.IEmployeeService;
import cn.lh.user.domain.Logininfo;
import cn.lh.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public List<Employee> findShopEmployees(Long shopId) {
        return employeeMapper.findByShopId(shopId);
    }

    @Override
    public void add(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.save(logininfo);
        employee.setLogininfo_id(logininfo.getId());
        super.add(employee);
        employeeMapper.saveEmployeeRole(employee.getId(), employee.getRole_id());
    }

    @Override
    public void del(Long id) {
        employeeMapper.removeEmployeeRoleByEmployeeId(id);
        super.del(id);
    }

    @Override
    public void update(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
        Logininfo logininfo = employee2Logininfo(employee);
        Long logininfo_id = employeeMapper.loadById(employee.getId()).getLogininfo_id();
        logininfo.setId(logininfo_id);
        logininfoMapper.update(logininfo);
        super.update(employee);
        employeeMapper.removeEmployeeRoleByEmployeeId(employee.getId());
        employeeMapper.saveEmployeeRole(employee.getId(), employee.getRole_id());
    }

    @Override
    public void batchDelete(Long[] ids) {
        for (Long id: ids) {
            del(id);
        }
    }

    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee, logininfo);
        logininfo.setType(0);
        return logininfo;
    }
}
